﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContentTypeSource.cs" company="Lambros Vasiliou">
//   © 2013
// </copyright>
// <summary>
//   Retrieves Content Types from a List.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace LV.EnhancedNew.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.SharePoint;

    /// <summary>
    /// Retrieves Content Types from a List.
    /// </summary>
    public class ContentTypeSource
    {
        /// <summary>
        /// Retrieve all Content Types from a List.
        /// </summary>
        /// <param name="listId">The ID of the list to interrogate</param>
        /// <param name="rootFolder">The folder in the document library where documents are to be saved at by the client.</param>
        /// <returns>A collection of <see cref="ContentType"/> in a generic list.</returns> 
        /// <remarks>The List must be in the same Web as the data source.</remarks>
        public List<ContentType> GetAllListContentTypes(string listId, string rootFolder)
        {
            if (!string.IsNullOrWhiteSpace(listId))
            {
                Guid listGuid;
                if (Guid.TryParse(listId, out listGuid))
                {
                    SPList list = SPContext.Current.Web.Lists[listGuid];
                    SPContentTypeCollection listContentTypes = list.ContentTypes;
                    var cTypes = from SPContentType contentType in listContentTypes
                                 where !(contentType.Hidden | contentType.Id.Parent.Equals(SPBuiltInContentTypeId.Folder))
                                 select new ContentType(contentType, rootFolder);

                    return cTypes.ToList();
                }

                throw new SPException("Invalid List ID.");
            }

            throw new SPException("You must load this page from a Library.");
        }
    }
}
